package routes

import (
	"class08/database"
	"class08/handlers"
	"class08/miiddleware"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

type Server interface {
	Run(addr ...string) (err error)
}

func setupRouter() *gin.Engine {
	//初始化数据库连接
	db, err := database.InitDB()
	if err != nil {
		log.Println(err)
	}
	//实现了很多方法 handlers包下面 Handlers
	h := handlers.Handlers{db}

	//路由
	r := gin.Default()

	r.POST("/signup", h.SignUp)

	r.POST("/signin", h.SignIn)

	//创建路由分组管理
	authorized := r.Group("/")
	//使用中间件
	authorized.Use(miiddleware.Auth())
	{
		authorized.POST("/todos", h.CreateTodo)
		authorized.GET("/todos", h.GetTodos)
		authorized.PUT("/todos/:id", h.UpdateTodo)
		authorized.DELETE("/todos/:id", h.DeleteTodo)
		authorized.POST("/signout", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{"message": "logged out"})
		})
	}
	return r
}

// 工厂模式
func NewServer() Server {
	return setupRouter()
}
